package network;

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder;

public class FileServer extends JFrame implements Runnable {

	private JPanel contentPane;
	private JButton btnNewButton;
	private JScrollPane scrollPane;
	private JTextArea result;
	
	static int staticport =4444;
	
	ObjectOutputStream send;
	ServerSocket server;
	String folder = "/download/";

//	/**
//	 * Launch the application.
//	 */
//	public static void main(String[] args) {
//		EventQueue.invokeLater(new Runnable() {
//			public void run() {
//				try {
//					FileServer frame = new FileServer();
//					frame.setVisible(true);
//				} catch (Exception e) {
//					e.printStackTrace();
//				}
//			}
//		});
//	}

	/**
	 * Create the frame.
	 */
	public FileServer(ObjectOutputStream send) {
		this.send = send;
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		contentPane.add(getBtnNewButton());
		contentPane.add(getScrollPane());

		// 만약 /download/ 폴더가 없으면 서버에 생성
		try {
			File f = new File(folder);
			if (!f.exists())
				f.mkdirs();
			
			staticport +=5;

		} catch (Exception ex) {

		}
	}

	private JButton getBtnNewButton() {
		if (btnNewButton == null) {
			btnNewButton = new JButton("서버시작");
			btnNewButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					Thread t = new Thread(FileServer.this);
					t.start();
				}
			});
			btnNewButton.setBounds(12, 10, 97, 23);
		}
		return btnNewButton;
	}

	private JScrollPane getScrollPane() {
		if (scrollPane == null) {
			scrollPane = new JScrollPane();
			scrollPane.setBounds(0, 59, 419, 193);
			scrollPane.setViewportView(getResult());
		}
		return scrollPane;
	}

	private JTextArea getResult() {
		if (result == null) {
			result = new JTextArea();
		}
		return result;
	}

	@Override
	public void run() {
		try {
			result.append("서버시작\n");
			server = new ServerSocket(staticport);
			
			// 클라이언트에게 서버의 아이피와 포트번호전송
			InetAddress ia = InetAddress.getLocalHost();
			String ip = ia.getHostAddress();
			ip+=","+staticport;
			
			SocketData sd = new SocketData("fileTransPort","server",null,ip);
			send.writeObject(sd);
			send.flush();
			
			
			result.append("쿨라이언트 대기중...\n");
			Socket socket = server.accept();

			result.append("클라이언트 접속됨\n");
			DataInputStream dis = new DataInputStream(socket.getInputStream());

			String fileName = dis.readUTF();
			result.append("수신된 파일명은" + fileName + "입니다.\n");
			int pos = fileName.lastIndexOf("\\");
			String tempFile = fileName.substring(pos + 1);
			result.append("저장될 파일명은" + folder + tempFile + "입니다.\n");
			FileOutputStream fos = new FileOutputStream(folder + tempFile);

			byte[] d = new byte[102400];
			int len = 0;

			while ((len = dis.read(d)) != -1) {
				fos.write(d, 0, len);
			}

			fos.close();
			dis.close();
			socket.close();
		} catch (Exception ex) {

		}

	}
}
